<template>
  <div class="pad-20 bgc-default" v-loading="loading">
    <!-- 订单信息 -->
    <div>
      <span class="font-20">订单信息</span>
      <div class="mar-t-10 bg-color-white pad-20">
        <el-row>
          <el-col :span="12">
            <table class="base-info">
              <tr>
                <td class="left">平台订单号：</td>
                <td class="right">
                  <div class="v-align-c">
                    <img class="width-16 height-16" :src="constant.platformIconObj[orderObj.externalPlatformType]"/>
                    <span class="mar-l-6">{{ orderObj.externalOrderNo }}</span>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="left">系统订单号：</td>
                <td class="right">{{ orderObj.orderNo }}</td>
              </tr>
              <tr>
                <td class="left">店铺名称：</td>
                <td class="right">{{ orderObj.shopName ? orderObj.shopName : '（店铺未找到）' }}</td>
              </tr>
            </table>
          </el-col>
          <el-col :span="12">
            <table class="base-info">
              <tr>
                <td class="left">收货人：</td>
                <td class="right">
                  <el-input v-model="orderObj.customerNickname" :disabled="isLock" class="width-300"></el-input>
                  <template v-if="orderObj.encryptReceiveFlag == 1">
                    <el-tooltip class="item" effect="dark" content="点击查看收货信息" placement="top-start">
                      <img :src="isLock ? lockIcon : unlockIcon" class="width-24 cursor-p mar-l-20" @click="doDecrypt(0)">
                    </el-tooltip>
                  </template>
                </td>
              </tr>
              <tr>
                <td class="left">收货人电话：</td>
                <td class="right">
                  <el-input v-model="orderObj.customerPhone" :disabled="isLock" class="width-300"></el-input>
                </td>
              </tr>
              <tr>
                <td class="left">收货地址：</td>
                <td class="right">
                  <el-select class="mar-r-3 width-140" v-model="orderObj.customerProvinceCode" :disabled="isLock" placeholder="请选择省份" @change="doChangeCity(orderObj.customerProvinceCode)">
                    <el-option v-for="item in provinceList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                  <el-select class="mar-r-3 width-140" v-model="orderObj.customerCityCode" :disabled="isLock" placeholder="请选择城市" @change="doChangeDistrict(orderObj.customerCityCode)">
                    <el-option v-for="item in cityList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                  <el-select v-model="orderObj.customerDistrictCode" :disabled="isLock" placeholder="请选择区县" class="width-140">
                    <el-option v-for="item in districtList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                  <div class="mar-t-5">
                    <el-input v-model="orderObj.customerAddress" :disabled="isLock" style="width: 435px"></el-input>
                  </div>
                </td>
              </tr>
            </table>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 平台商品明细 -->
    <div class="mar-t-20">
      <span class="font-20">换货信息</span>
      <div class="mar-t-10 bg-color-white pad-20">
        <div class="mar-b-20">
          <label>换货运费：</label>
          <el-input v-model="orderObj.freight"
            class="width-300"
            @keyup.native="orderObj.freight = checkInputNum(orderObj.freight)">
            <template slot="append">元</template>
          </el-input>
        </div>
        <div class="mar-b-20">
          <div class="mar-b-10"><label>订单原商品：</label></div>
          <el-table :data="orderObj.orderGoodsList">
            <el-table-column min-width="250px" label="订单商品">
              <template slot-scope="scope">
                <div class="flex v-align-c">
                  <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                  <div class="pad-l-10">
                    <div class="line-2">{{ scope.row.goodsTitle }}</div>
                    <br>
                    <div>外部编码：{{ scope.row.externalCode }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="180px" label="规格描述" prop="skuDetail" align="left">
            </el-table-column>
            <el-table-column width="130px" label="数量" prop="goodsNum" align="center">
            </el-table-column>
            <el-table-column width="130px" label="单价" prop="goodsPrice" align="center">
            </el-table-column>
            <el-table-column width="130px" label="支付金额" prop="goodsPayAmount" align="center">
            </el-table-column>
            <el-table-column width="100px" align="center">
            </el-table-column>
          </el-table>
        </div>

        <div class="mar-b-20">
          <div class="mar-b-10"><label>待换货商品：</label></div>
          <el-button type="text" size="medium" @click="doAddSku()">添加商品</el-button>
          <el-table :data="changeGoodsList">
            <el-table-column min-width="250px" label="换货商品">
              <template slot-scope="scope">
                <div class="flex v-align-c">
                  <label><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                  <div class="pad-l-10">
                    <template v-if="scope.row.goodsId">
                      <div class="line-2">{{ scope.row.goodsTitle }}</div>
                      <br>
                      <div>外部编码：{{ scope.row.externalCode }}</div>
                    </template>
                    <template v-else>
                      <div>（未选择）</div>
                    </template>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="180px" label="换货规格" prop="skuDetail" align="left">
              <template slot-scope="scope">
                <div>{{ scope.row.goodsId ? scope.row.skuDetail : '（未选择）' }}</div>
              </template>
            </el-table-column>
            <el-table-column width="130px" label="换货数量" prop="goodsNum" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.goodsNum"
                  class="width-80"
                  @keyup.native="scope.row.goodsNum = checkInputPositiveNum(scope.row.goodsNum)">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column width="130px" label="换货单价" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.externalGoodsPrice"
                  class="width-100"
                  @keyup.native="scope.row.externalGoodsPrice = checkInputNum(scope.row.externalGoodsPrice)">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column width="130px" label="换货金额" align="center">
              <template slot-scope="scope">
                <span>{{ (scope.row.goodsNum * scope.row.externalGoodsPrice).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column width="100px" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="medium" @click="doRemove(scope)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 底部按钮区 -->
    <div class="pad-20" align="center">
      <el-button type="primary" :disabled="isLock" @click="doConfirm">确认下单</el-button>
    </div>

    <!-- 选择商品dialog -->
    <el-dialog width="1000px" v-el-drag-dialog title="选择商品" :visible.sync="selectSkuVisible">
      <select-goods-sku :showFlag="selectSkuVisible" :skuFlag="1"
       :crossBorderType="1"
       @callback="doCallbackSelect">
      </select-goods-sku>
    </el-dialog>

  </div>
</template>

<script>
  import { getOrder, doChangeOrder } from '@/api/goods/order'
  import { listProvince, listCity, listDistrict } from '@/api/area/area'
  import { decryptReceiveInfo } from '@/api/goods/thirdOrder'
  import elDragDialog from '@/directive/el-dragDialog'
  import selectGoodsSku from '@/views/goods/order/components/select-goods-sku'
  import unlockIcon from '@/assets/images/unlock-icon.png'
  import lockIcon from '@/assets/images/lock-icon.png'

  export default {
    directives: {
      elDragDialog
    },
    components: {
      selectGoodsSku
    },
    data() {
      return {
        // 第三方订单对象
        orderObj: {
          orderId: '',
          orderNo: '',
          enterpriseId: '',
          memberId: '',
          payType: '',
          externalPlatformType: '',
          externalOrderNo: '',
          shopName: '',
          customerNickname: '',
          customerPhone: '',
          customerProvinceCode: '',
          customerCityCode: '',
          customerDistrictCode: '',
          customerAddress: '',
          freight: '0',
          orderGoodsList: []
        },
        // 换货商品集合
        changeGoodsList: [],
        // 省集合
        provinceList: [],
        // 市集合
        cityList: [],
        // 区集合
        districtList: [],
        loading: false,
        selectSkuVisible: false,
        // 锁图标
        lockIcon,
        unlockIcon,
        // 锁标识
        isLock: false
      }
    },
    // 初始化页面
    created() {
      // 获取省信息
      listProvince().then(response => {
        this.provinceList = response.data
      })
      const orderId = this.getCurrentPage().query.orderId
      this.orderObj.orderId = orderId
      this.init()
    },
    methods: {
      // 初始化
      init() {
        this.loading = true
        getOrder(this.orderObj.orderId).then(response => {
          this.loading = false
          if (response.isError) return
          Object.assign(this.orderObj, response.data)
          this.isLock = this.orderObj.encryptReceiveFlag === 1
          this.doChangeCity(this.orderObj.customerProvinceCode, this.orderObj.customerCityCode, this.orderObj.customerDistrictCode)
        })
      },
      // 解密事件
      doDecrypt(decryptReportType) {
        if (!this.isLock) {
          // 不再解密
          return
        }
        this.loading = true
        decryptReceiveInfo(this.orderObj.externalOrderNo, this.orderObj.externalPlatformType, decryptReportType).then(response => {
          this.loading = false
          if (response.isError) return
          this.isLock = false
          const data = response.data
          this.orderObj.customerNickname = data.customerName
          this.orderObj.customerPhone = data.customerPhone
          this.orderObj.customerAddress = data.customerAddress
        })
      },
      // 市修改事件
      doChangeCity(provinceCode, cityCode, townCode) {
        this.cityList = []
        this.districtList = []
        this.orderObj.customerCityCode = ''
        this.orderObj.customerDistrictCode = ''
        if (provinceCode) {
          listCity(provinceCode).then(response => {
            this.cityList = response.data
          })
          this.orderObj.customerCityCode = cityCode
          this.doChangeDistrict(cityCode, townCode)
        }
      },
      // 区修改事件
      doChangeDistrict(cityCode, townCode) {
        this.districtList = []
        this.orderObj.customerDistrictCode = ''
        if (cityCode) {
          listDistrict(cityCode).then(response => {
            this.districtList = response.data
          })
          this.orderObj.customerDistrictCode = townCode
        }
      },
      // 添加商品事件
      doAddSku() {
        this.selectSkuVisible = true
      },
      // 商品选择回调事件
      doCallbackSelect(res) {
        const exist = this.changeGoodsList.filter(item => item.skuId === res.skuId)
        if (exist.length === 0) {
          const goods = {
            goodsId: res.goodsId,
            goodsNum: 1,
            externalGoodsPrice: 0,
            goodsTitle: res.title,
            goodsImageUrl: res.imageUrl,
            externalCode: res.externalCode,
            skuId: res.skuId,
            skuDetail: res.skuDetail
          }
          this.changeGoodsList.push(goods)
          this.selectSkuVisible = false
        } else {
          this.$message({ message: '商品已添加', type: 'error' })
        }
      },
      // 移除事件
      doRemove(scope) {
        this.changeGoodsList.splice(scope.$index, 1)
      },
      // 确定事件
      doConfirm() {
        if (!this.orderObj.customerNickname) {
          this.$message({ message: '收货人不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerPhone) {
          this.$message({ message: '收货人电话不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerProvinceCode) {
          this.$message({ message: '省不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerCityCode) {
          this.$message({ message: '市不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerDistrictCode) {
          this.$message({ message: '区不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerAddress) {
          this.$message({ message: '详细地址不能为空', type: 'error' })
          return
        }
        const validGoodsList = this.changeGoodsList.filter(item => item.goodsId)
        if (validGoodsList.length === 0) {
          this.$message({ message: '请选择换货商品', type: 'error' })
          return
        }
        const goodsNumList = validGoodsList.filter(item => !item.goodsNum)
        if (goodsNumList.length > 0) {
          this.$message({ message: '存在换货数量为0的换货商品，请设置换货数量', type: 'error' })
          return
        }
        const form = {
          originalNo: this.orderObj.externalOrderNo,
          externalPlatformType: this.orderObj.externalPlatformType,
          enterpriseId: this.orderObj.enterpriseId,
          memberId: this.orderObj.memberId,
          customerNickname: this.orderObj.customerNickname,
          customerPhone: this.orderObj.customerPhone,
          customerProvinceCode: this.orderObj.customerProvinceCode,
          customerCityCode: this.orderObj.customerCityCode,
          customerDistrictCode: this.orderObj.customerDistrictCode,
          customerAddress: this.orderObj.customerAddress,
          freight: this.orderObj.freight,
          payType: this.orderObj.payType
        }
        const goodsList = []
        validGoodsList.forEach(e => {
          const goods = {
            'externalGoodsPrice': e.externalGoodsPrice,
            'goodsId': e.goodsId,
            'skuId': e.skuId,
            'goodsNum': e.goodsNum
          }
          goodsList.push(goods)
        })
        form.goodsList = goodsList
        this.loading = true
        doChangeOrder(form).then(response => {
          this.loading = false
          if (response.isError) return
          this.$message({ message: '下单成功', type: 'success' })
          this.$router.push({ path: '/order/change-order' })
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .base-info {
    width: 100%;
    line-height: 30px;
    .left {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
